# -*- coding: utf-8 -*-
from django.db import models
from django import forms
from django.utils.translation import ugettext as _
import datetime

### MODELES ###

    ## Génériques ##
    
class Coordonnees(models.Model):
    longitude = models.FloatField(default=0)
    latitude = models.FloatField(default=0)
    adresse = models.TextField(default='')
    
class Invitation(models.Model):
    date = models.DateField(default=datetime.date.today())
    heure = models.TimeField(default=datetime.time(0))
    coord_barycentre = models.ForeignKey(Coordonnees, default=None, blank=True, null=True)
    dict = models.CharField(max_length=900, default='')

def set_dict(invit):
    dict = "{'GO':u'Type de restaurant', 'BU':u'Budget', 'DI':u'Distance', "
    dict+= "'FF':u'Fast-Food', 'AS':u'Asiatique','FR':u'Français','IT':u'Italien','OR':u'Oriental', "
    dict+= "'MC':u'Moins cher', 'PC':u'Plus cher', 'ML':u'Moins loin', 'PL':u'Plus loin', "
    i = 0
    questions = invit.question_set.all()
    for quest in questions:
        if quest.champ=="Type de restaurant" or quest.champ=="Distance" or quest.champ=="Budget":
            pass
        else:
            dict += "'CU" + str(i) + "':'" + quest.champ + "', "
            j = 0
            for rep in quest.reponse_set.all():
                dict += "'CU" + str(i) + "R" + str(j) + "':'" + rep.champ + "', "
                j+=1
            i+=1
    dict += "}"
    return dict
  
class Invite(models.Model):
    nom = models.CharField(max_length=200, default='')
    prenom = models.CharField(max_length=200, default='')
    email = models.EmailField(max_length=200, default='')
    invit = models.ForeignKey(Invitation, default=None, blank=True, null=True)
    presence = models.BooleanField(default=False)
    coord = models.ForeignKey(Coordonnees, default=None, blank=True, null=True)
    confirm = models.BooleanField(default=False)
    lang = models.CharField(max_length=200)
    def __unicode__(self):
        return self.prenom + " " + self.nom
    
    ## Optimisation ##
    
class Critere(models.Model):
    type = models.CharField(max_length=200, default='')
    nbre_etoile = models.IntegerField(default=0)
    invite = models.ForeignKey(Invite)

class Detail(models.Model):
    detail = models.CharField(max_length=200, default='')
    critere = models.ForeignKey(Critere)
    
class Question(models.Model):
    champ = models.CharField(max_length=200)
    invit = models.ForeignKey(Invitation)
    def __unicode__(self):
        return self.champ
    
class Reponse(models.Model):
    champ = models.CharField(max_length=200)
    question = models.ForeignKey(Question)
    def __unicode__(self):
        return self.champ
    
    ## Restaurant ##

class Restaurant(models.Model):
    nom = models.CharField(max_length=200, default='')
    coord = models.ForeignKey(Coordonnees)
    type = models.IntegerField()
    invit = models.ForeignKey(Invitation)
    url = models.CharField(max_length=200, default='')
    choisi = models.BooleanField(default=False)
    dist = models.FloatField(default=0)
        
### FORMULAIRES ###    

class InvitationForm(forms.Form):
    date = forms.DateField(initial=datetime.date.today(), label='Date', 
                           widget=forms.DateInput(format = '%Y/%m/%d'), input_formats=('%Y/%m/%d',))
    heure = forms.TimeField(label = 'Heure', initial=datetime.time(14))

class OrganisationForm(forms.Form):
    nom_orga = forms.CharField(max_length=200, label='Nom')
    prenom_orga = forms.CharField(max_length=200, label= 'Prénom')
    email_orga = forms.EmailField(label= "Adresse e-mail")

class LangueForm(forms.Form):
    lang = forms.CharField(max_length=200)
    def __init__(self, *args, **kwargs):
        super(LangueForm,self).__init__(*args, **kwargs)
        self.fields['lang'].widget = forms.Select(choices = (('fr', 'Français'),('en', 'English')))
         
class InviteForm(forms.Form):
    email_invite = forms.EmailField(label = "Adresse e-mail")
    
class AdresseForm(forms.Form):
    adresse = forms.CharField(label='Adresse')
    def __init__(self, *args, **kwargs):
        if 'adr' in kwargs:
            adr = kwargs.pop('adr')
            super(AdresseForm,self).__init__(*args, **kwargs)
            self.fields['adresse'].initial = adr
        else:
            super(AdresseForm,self).__init__(*args, **kwargs)
            self.fields['adresse'].initial = 'La Défense, Paris'
    
class MultiRepForm(forms.Form):
    question = forms.CharField(max_length=200, label='Question', required=False)
    reponses = forms.CharField(label='Reponses', widget=forms.Textarea, required=False)
    
class SelectCritereForm(forms.Form):
    type_restaurant = forms.BooleanField(label='Type de restaurant', required=False, initial=True)
    budget = forms.BooleanField(label='Budget', required=False, initial=True)
    distance = forms.BooleanField(label='Distance', required=False, initial=True)
    
def set_choices_type(invit): 
    # rend le tuple de type possible pour le sondage de l'invitation correspondante
    questions = invit.question_set.all()
    rep = []
    i = 0
    for quest in questions:
        if quest.champ=="Type de restaurant":
            tuple = 'GO', _(u'Type de restaurant')
            rep.append(tuple)
        elif quest.champ=="Budget":
            tuple = 'BU', _(u'Budget')
            rep.append(tuple)
        elif quest.champ=="Distance":
            tuple = 'DI', _(u'Distance')
            rep.append(tuple)
        else:
            tag = 'CU' + str(i)
            tuple = tag, quest.champ
            rep.append(tuple)
            i+=1
    return rep

def set_choices_detail(invit):
    # rend le tuple de detail possible pour le sondage de l'invitation correspondante
    questions = invit.question_set.all()
    rep = []
    i = 0
    for quest in questions:
        if quest.champ=="Type de restaurant":
            tuple = 'FF', _(u'Fast-Food')
            rep.append(tuple)
            tuple = 'AS', _(u'Asiatique')
            rep.append(tuple)
            tuple = 'FR', _(u'Français')
            rep.append(tuple)
            tuple = 'IT', _(u'Italien')
            rep.append(tuple)
            tuple = 'OR', _(u'Oriental')
            rep.append(tuple)
        elif quest.champ=="Budget":
            tuple = 'MC', _(u'Moins cher')
            rep.append(tuple)
            tuple = 'PC', _(u'Plus cher')
            rep.append(tuple)
        elif quest.champ=="Distance":
            tuple = 'ML', _(u'Moins loin')
            rep.append(tuple)
            tuple = 'PL', _(u'Plus loin')
            rep.append(tuple)
        else:
            j = 0
            for reponse in quest.reponse_set.all():
                tag = 'CU' + str(i) + 'R' + str(j)
                tuple = tag, reponse.champ
                rep.append(tuple)
                j+=1
            i+=1
    return rep
    
class ChoiceForm(forms.Form):
    type = forms.CharField(label="Type")
    detail = forms.CharField(label='Detail')
    nbre_etoile = forms.CharField(label='Note')
    def __init__(self, *args, **kwargs):
        NOTATION_CHOICES = (
                ('1', '1'),
                ('2', '2'),
                ('3', '3'),
                ('4', '4'),
                ('5', '5'),
                        )
        if 'invit' in kwargs:
            invit = kwargs.pop('invit')
            super(ChoiceForm,self).__init__(*args, **kwargs)
            self.fields['type'].widget = forms.Select(attrs={'onchange': "Dajaxice.EssaiAVA.ava.updatecombo(Dajax.process,{'option':this.value, 'id': this.id, 'invit_id': invit_id})"}, choices=set_choices_type(invit))
            self.fields['detail'].widget = forms.Select(attrs={'onchange': "Dajaxice.EssaiAVA.ava.updateselected(Dajax.process,{'selected':this.value, 'id': this.id, 'invit_id': invit_id})"}, choices=set_choices_detail(invit))     
            self.fields['nbre_etoile'].widget = forms.Select(attrs={'class':'rating'}, choices = NOTATION_CHOICES)
